<?php

function doMsg($msg,$username,$password) {
	
	$url = 'http://twitter.com/statuses/update.xml'; //Sends a message
	
	$curl_handle = curl_init();
	
	curl_setopt($curl_handle, CURLOPT_URL, "$url");
	curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
	curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curl_handle, CURLOPT_POST, 1);
	curl_setopt($curl_handle, CURLOPT_USERPWD, "$username:$password");	
	
	
	curl_setopt($curl_handle, CURLOPT_POSTFIELDS, "status=$msg");
	
	$buffer = curl_exec($curl_handle);
	curl_close($curl_handle);
	
	// check for success or failure
	if (empty($buffer)) {
	    return 'fail';
	} else {
	    return 'success';
	}	
}

function followUser($tid,$username,$password) {
	$url = 'http://twitter.com/friendships/create/'.$tid.'.json'; // gets timeline (authenticate first)
			
	$curl_handle = curl_init();
	
	curl_setopt($curl_handle, CURLOPT_URL, "$url");
	curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
	curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curl_handle, CURLOPT_POST, 1);
	curl_setopt($curl_handle, CURLOPT_USERPWD, "$username:$password");	

	
	$buffer = curl_exec($curl_handle);
	curl_close($curl_handle);
	
	// check for success or failure
	if (empty($buffer)) {
	    return 'success';
	} else {
		return 'fail';
	}
	
}

$msg = $_POST['twitter_message']; $msg = str_replace("\'","'",$msg);
$username = $_POST['twitter_username'];
$password = $_POST['twitter_password'];
$redirect = $_POST['twitter_redirect'];
$follow = $_POST['twitter_follow'];
$follow_name = $_POST['twitter_follow_name'];

//where they came from
$ref=@$HTTP_REFERER;

if($msg!="" && $username!="" && $password!="" && $redirect!="") {
	doMsg($msg,$username,$password);
	if($follow=="on") { 
		followUser($follow_name,$username,$password); 
	}
	
	header( "HTTP/1.1 301 Moved Permanently" ); 
	header( "Location: $redirect"); 
} else { ?>
	<div align="center" style="font-family:Arial; font-size;8pt; margin:50px auto; padding:10px; border:1px dotted GRAY; width:800px; background-color:#FFFFCC;">
		<strong>Please Complete the Form</strong><br/><a href="<?php echo $ref.'#__vt';?>">Go Back</a></div>
<?php } ?>
